#include "loginwindow.h"
#include "ui_loginwindow.h"
#include "welcomewindow.h"
#include<QDebug>
#include<QList>
#include<QJsonArray>
#include<QJsonDocument>
#include<QJsonObject>
#include<QJsonValue>
#include<QMessageBox>
#include<QTcpSocket>
#include<QByteArray>
#include<QFile>
#include<QDir>

#define serverPath "./data/serverIP.txt"
#define SERVER_PROT 6065
bool isConnected=false;
loginWindow::loginWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::loginWindow)
{
    ui->setupUi(this);
    this->socket=new QTcpSocket;

    connect(socket,&QIODevice::readyRead,this,&loginWindow::readData);
}

loginWindow::~loginWindow()
{
    delete ui;
}


void loginWindow::on_pushButton_clicked()
{
    if(!isConnected)
    {   isConnected=true;

        connect(socket,&QTcpSocket::connected,this,&loginWindow::connectedTohost);
        socket->connectToHost(ui->IpEdit->text(),SERVER_PROT);


    }
    else
    {
        connectedTohost();
    }




}

void loginWindow::connectedTohost()
{
        QFile *server=new QFile(serverPath);
       if(!server->open(QIODevice::WriteOnly|QIODevice::Truncate))
       {
            qDebug()<<"open serverPath failed";
       }
       server->write(ui->IpEdit->text().toUtf8());
        server->close();
         QString data=QString("login#"+ui->comboBox->currentText()+"#"+ui->acountEdit->text()+"#"+ui->passwordEdit->text());
         QByteArray data1= QByteArray(data.toUtf8());
         socket->write(data1);


}


void loginWindow::readData()
{
    QByteArray data=socket->readAll();

    if(data.split(':')[0]=="登录成功"&&data.split(':')[1]=="管理员")
    {
        welcomeWindow *w1=new welcomeWindow;
        w1->setnotice("*管理员*"+ui->acountEdit->text());
        w1->show();
        socket->disconnectFromHost();
        socket->close();
        this->close();
    }
    else if(data.split(':')[0]=="登录成功"&&data.split(':')[1]=="员工")
    {
        welcomeWindow *w1=new welcomeWindow;
        w1->setnotice("*员工*"+ui->acountEdit->text());
        w1->show();
        socket->disconnectFromHost();
        socket->close();
        this->close();
    }
    else if(data.split(':')[0]=="登录失败"&&data.split(':')[1]=="密码错误")
    {
        QMessageBox::critical(this,"登录失败","密码错误，请重新输入");

    }
    else if(data.split(':')[0]=="登录失败"&&data.split(':')[1]=="用户不存在")
    {
        QMessageBox::critical(this,"登录失败","此账号不存在");

    }
    else if(data.split(':')[0]=="登录失败"&&data.split(':')[1]=="身份选择有误")
    {
        QMessageBox::critical(this,"登录失败","身份选择有误,请重新选择");
    }
}
